<template>
	<view class="add-log-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-back" @click="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<text class="nav-title">添加健康记录</text>
			<view class="nav-submit" @click="submitLog">提交</view>
		</view>
		<!-- 记录表单 -->
		<view class="log-form">
			<!-- 标题输入 -->
			<view class="form-section">
				<view class="section-title">标题</view>
				<view class="input-wrapper">
					<input class="form-input" type="text" v-model="logForm.title" placeholder="请输入记录标题"
						maxlength="20" />
					<text class="input-count">{{logForm.title.length}}/20</text>
				</view>
			</view>

			<!-- 描述内容 -->
			<view class="form-section">
				<view class="section-title">描述</view>
				<view class="textarea-wrapper">
					<textarea class="form-textarea" v-model="logForm.description" placeholder="请详细描述宠物的健康状况..."
						maxlength="200"></textarea>
					<text class="input-count textarea-count">{{logForm.description.length}}/200</text>
				</view>
			</view>

			<!-- 日期时间选择 -->
			<view class="form-section">
				<view class="section-title">记录时间</view>
				<view class="datetime-picker">
					<view class="date-picker" @click="openDatePicker">
						<text class="picker-value">{{logForm.date || '选择日期'}}</text>
						<text class="iconfont icon-calendar"></text>
					</view>
					<view class="time-picker" @click="openTimePicker">
						<text class="picker-value">{{logForm.time || '选择时间'}}</text>
						<text class="iconfont icon-time"></text>
					</view>
				</view>
			</view>-
		</view>

		<!-- 提交按钮 -->
		<view class="submit-button-area">
			<view class="submit-button" @click="submitLog">
				<text>保存记录</text>
			</view>
		</view>

		<!-- 底部安全区域 -->
		<view class="safe-bottom"></view>
	</view>
</template>

<script>
	import {
		userApi
	} from '@/api/user.js'

	export default {
		data() {
			return {
				petId: '',
				petInfo: {
					id: '123456',
					name: '小毛球',
					avatar: '/static/pet-test.png'
				},
				logTypes: [{
						name: '饮食',
						value: 'diet',
						icon: 'icon-diet'
					},
					{
						name: '体重',
						value: 'weight',
						icon: 'icon-weight'
					},
					{
						name: '体温',
						value: 'temperature',
						icon: 'icon-temperature'
					},
					{
						name: '运动',
						value: 'activity',
						icon: 'icon-activity'
					},
					{
						name: '服药',
						value: 'medicine',
						icon: 'icon-medicine'
					},
					{
						name: '体检',
						value: 'examination',
						icon: 'icon-examination'
					},
					{
						name: '症状',
						value: 'symptom',
						icon: 'icon-symptom'
					},
					{
						name: '其他',
						value: 'other',
						icon: 'icon-other'
					}
				],
				selectedType: 'diet',
				showHealthMetrics: true,
				logForm: {
					title: '',
					description: '',
					date: this.formatDate(new Date()),
					time: this.formatTime(new Date()),
					images: [],
					metrics: {
						weight: '',
						temperature: '',
						foodAmount: '',
						waterAmount: '',
						activityDuration: ''
					},
					reminder: {
						enabled: false,
						type: 'once',
						time: '',
						note: ''
					}
				}
			}
		},
		methods: {
			// 格式化日期为 YYYY-MM-DD
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 格式化时间为 HH:MM
			formatTime(date) {
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			// 获取宠物基本信息
			getPetInfo() {
				// 实际应用中，这里会调用API获取宠物信息
				// uni.request({
				//   url: 'api/pet/info',
				//   method: 'GET',
				//   data: { petId: this.petId },
				//   success: (res) => {
				//     this.petInfo = res.data;
				//   }
				// });

				// 使用静态数据模拟
				console.log('获取宠物信息，ID:', this.petId);
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 选择记录类型
			selectLogType(type) {
				this.selectedType = type;

				// 根据类型决定是否显示健康指标
				const metricsTypes = ['diet', 'weight', 'temperature', 'activity', 'examination'];
				this.showHealthMetrics = metricsTypes.includes(type);

				// 清空之前的指标数据
				this.logForm.metrics = {
					weight: '',
					temperature: '',
					foodAmount: '',
					waterAmount: '',
					activityDuration: ''
				};

				// 根据类型设置默认标题
				const titleMap = {
					diet: '日常饮食',
					weight: '体重记录',
					temperature: '体温记录',
					activity: '运动记录',
					medicine: '服药记录',
					examination: '体检记录',
					symptom: '症状记录',
					other: '其他记录'
				};

				this.logForm.title = titleMap[type] || '';
			},

			// 打开日期选择器
			openDatePicker() {
				uni.showDatePicker({
					current: this.logForm.date,
					success: (res) => {
						this.logForm.date = res.date;
					}
				});
			},

			// 打开时间选择器
			openTimePicker() {
				uni.showTimeSelector({
					current: this.logForm.time,
					success: (res) => {
						this.logForm.time = res.time;
					}
				});
			},

			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 4 - this.logForm.images.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						// 合并新选择的图片
						this.logForm.images = [...this.logForm.images, ...res.tempFilePaths];
					}
				});
			},

			// 删除已选择的图片
			deleteImage(index) {
				this.logForm.images.splice(index, 1);
			},

			// 切换提醒开关
			toggleReminder(e) {
				this.logForm.reminder.enabled = e.detail.value;

				// 如果开启提醒，设置默认时间
				if (this.logForm.reminder.enabled && !this.logForm.reminder.time) {
					const now = new Date();
					this.logForm.reminder.time = this.formatTime(now);
				}
			},

			// 设置提醒类型
			setReminderType(type) {
				this.logForm.reminder.type = type;
			},

			// 打开提醒时间选择器
			openReminderTimePicker() {
				uni.showTimeSelector({
					current: this.logForm.reminder.time || this.formatTime(new Date()),
					success: (res) => {
						this.logForm.reminder.time = res.time;
					}
				});
			},

			// 验证表单
			validateForm() {
				if (!this.logForm.title.trim()) {
					uni.showToast({
						title: '请输入记录标题',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.description.trim()) {
					uni.showToast({
						title: '请输入记录描述',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.date) {
					uni.showToast({
						title: '请选择记录日期',
						icon: 'none'
					});
					return false;
				}

				if (!this.logForm.time) {
					uni.showToast({
						title: '请选择记录时间',
						icon: 'none'
					});
					return false;
				}

				// 验证提醒相关信息
				if (this.logForm.reminder.enabled) {
					if (!this.logForm.reminder.time) {
						uni.showToast({
							title: '请选择提醒时间',
							icon: 'none'
						});
						return false;
					}

					if (!this.logForm.reminder.note.trim()) {
						uni.showToast({
							title: '请输入提醒内容',
							icon: 'none'
						});
						return false;
					}
				}

				return true;
			},

			// 提交记录
			submitLog() {
				if (!this.validateForm()) {
					return;
				}

				// 构建提交的数据
				const logData = {
					userId: uni.getStorageSync('userId'),
					type: this.selectedType,
					title: this.logForm.title,
					content: this.logForm.description,
					createTime: `${this.logForm.date} ${this.logForm.time}:00`,
					metrics: this.showHealthMetrics ? this.logForm.metrics : null,
					reminder: this.logForm.reminder.enabled ? this.logForm.reminder : null
				};
				const result = userApi.addHealthRecords(logData)

				// 显示加载提示
				uni.showLoading({
					title: '保存中...'
				});

				console.log('提交的数据:', logData);

				// 这里是静态演示，实际应用中，这里会上传图片和提交表单数据
				// 先上传图片，获取到图片URL后再提交表单
				setTimeout(() => {
					// 模拟上传成功
					uni.hideLoading();
					uni.showToast({
						title: '保存成功',
						icon: 'success',
						success: () => {
							// 延迟返回上一页
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/health/healthFiles'
								});
							}, 1500);
						}
					});
				}, 1000);

				// 实际应用中的代码示例:
				/*
				// 1. 先上传图片
				const uploadPromises = this.logForm.images.map(imgPath => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'api/upload',
							filePath: imgPath,
							name: 'file',
							success: (res) => {
								const data = JSON.parse(res.data);
								resolve(data.url);
							},
							fail: (err) => {
								reject(err);
							}
						});
					});
				});
				
				Promise.all(uploadPromises).then(imageUrls => {
					// 2. 图片上传完成后，提交表单数据
					logData.images = imageUrls;
					
					uni.request({
						url: 'api/pet/health-log',
						method: 'POST',
						data: logData,
						success: (res) => {
							uni.hideLoading();
							if (res.data.success) {
								uni.showToast({
									title: '保存成功',
									icon: 'success',
									success: () => {
										// 延迟返回上一页
										setTimeout(() => {
											uni.navigateBack();
										}, 1500);
									}
								});
							} else {
								uni.showToast({
									title: res.data.message || '保存失败',
									icon: 'none'
								});
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					});
				}).catch(() => {
					uni.hideLoading();
					uni.showToast({
						title: '图片上传失败',
						icon: 'none'
					});
				});
				*/
			}
		}
	}
</script>

<style scoped>
	.add-log-container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 导航栏样式 */
	.nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		height: 170rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.nav-back {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.nav-submit {
		font-size: 28rpx;
		color: #F9CB43;
	}

	/* 宠物信息栏 */
	.pet-info-bar {
		margin-top: 90rpx;
		background-color: #F9CB43;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
	}

	.pet-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
		border: 3rpx solid #fff;
	}

	.pet-name {
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
	}

	/* 表单区域样式 */
	.log-form {
		padding: 20rpx 30rpx;
		margin-top: 180rpx;
	}

	.form-section {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
	}

	.section-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
	}

	/* 记录类型选择 */
	.log-type-list {
		display: flex;
		flex-wrap: wrap;
	}

	.log-type-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15rpx 0;
		transition: all 0.3s;
	}

	.log-type-item .iconfont {
		font-size: 40rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.type-name {
		font-size: 24rpx;
		color: #666;
	}

	.type-active {
		background-color: rgba(249, 203, 67, 0.1);
		border-radius: 10rpx;
	}

	.type-active .iconfont {
		color: #F9CB43;
	}

	.type-active .type-name {
		color: #F9CB43;
	}

	/* 输入框样式 */
	.input-wrapper {
		position: relative;
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		overflow: hidden;
		height: 80rpx;
	}

	.form-input {
		height: 80rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.input-count {
		position: absolute;
		right: 20rpx;
		bottom: 10rpx;
		font-size: 24rpx;
		color: #999;
	}

	/* 文本域样式 */
	.textarea-wrapper {
		position: relative;
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		overflow: hidden;
		padding: 20rpx;
	}

	.form-textarea {
		width: 100%;
		height: 180rpx;
		font-size: 28rpx;
	}

	.textarea-count {
		position: absolute;
		right: 20rpx;
		bottom: 20rpx;
	}

	/* 日期时间选择器 */
	.datetime-picker {
		display: flex;
	}

	.date-picker,
	.time-picker {
		flex: 1;
		background-color: #f9f9f9;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		border-radius: 10rpx;
	}

	.date-picker {
		margin-right: 20rpx;
	}

	.picker-value {
		font-size: 28rpx;
		color: #333;
	}

	/* 图片上传 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
	}

	.image-item,
	.upload-btn {
		width: 150rpx;
		height: 150rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		overflow: hidden;
		position: relative;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 0 0 0 10rpx;
	}

	.delete-btn .iconfont {
		font-size: 28rpx;
		color: #fff;
	}

	.upload-btn {
		background-color: #f9f9f9;
		border: 1rpx dashed #ddd;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.upload-btn .iconfont {
		font-size: 40rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.upload-tip {
		font-size: 22rpx;
		color: #999;
		margin-top: 10rpx;
	}

	/* 健康指标 */
	.metrics-form {
		display: flex;
		flex-wrap: wrap;
	}

	.metric-item {
		width: 50%;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}

	.metric-label {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 10rpx;
		display: block;
	}

	.metric-input-wrapper {
		display: flex;
		align-items: center;
		height: 70rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		padding: 0 20rpx;
	}

	.metric-input {
		flex: 1;
		height: 70rpx;
		font-size: 26rpx;
	}

	.metric-unit {
		font-size: 26rpx;
		color: #999;
		margin-left: 10rpx;
	}

	/* 提醒设置 */
	.reminder-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.reminder-type {
		display: flex;
		margin-bottom: 20rpx;
	}

	.reminder-type-item {
		flex: 1;
		height: 70rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f9f9f9;
		margin-right: 10rpx;
		border-radius: 10rpx;
		font-size: 26rpx;
		color: #666;
	}

	.reminder-type-item:last-child {
		margin-right: 0;
	}

	.reminder-time-picker {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
		margin-bottom: 20rpx;
	}

	.reminder-time-label {
		font-size: 26rpx;
		color: #666;
	}

	.reminder-time-value {
		display: flex;
		align-items: center;
		font-size: 26rpx;
		color: #333;
	}

	.reminder-time-value .iconfont {
		margin-left: 10rpx;
		font-size: 24rpx;
		color: #999;
	}

	.reminder-note {
		display: flex;
		align-items: center;
		height: 80rpx;
		padding: 0 20rpx;
		background-color: #f9f9f9;
		border-radius: 10rpx;
	}

	.reminder-note-label {
		width: 150rpx;
		font-size: 26rpx;
		color: #666;
	}

	.reminder-note-input {
		flex: 1;
		height: 80rpx;
		font-size: 26rpx;
	}

	/* 提交按钮 */
	.submit-button-area {
		padding: 20rpx 30rpx 40rpx;
	}

	.submit-button {
		height: 90rpx;
		background-color: #F9CB43;
		border-radius: 45rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 30rpx;
		font-weight: bold;
		box-shadow: 0 4rpx 12rpx rgba(249, 203, 67, 0.3);
	}

	.safe-bottom {
		height: 50rpx;
	}

	/* 图标字体 */
	.iconfont {
		font-family: "iconfont";
		font-size: 36rpx;
		color: #F9CB43;
	}
</style>